package top.javatool.canal.client.spring.boot.autoconfigure;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import top.javatool.canal.client.handler.CanalThreadUncaughtExceptionHandler;
import top.javatool.canal.client.spring.boot.properties.CanalProperties;

import java.util.concurrent.*;

/**
 * @author yang peng
 * @date 2019/4/1915:19
 */
@Slf4j
@Configuration
@ConditionalOnProperty(value = CanalProperties.CANAL_ASYNC, havingValue = "true", matchIfMissing = true)
public class ThreadPoolAutoConfiguration {
    @Bean(destroyMethod = "shutdown")
    public ExecutorService executorService() {
        int processors = Runtime.getRuntime().availableProcessors();
        log.info("当前操作系统可用处理器个数：" + processors);
        CanalThreadUncaughtExceptionHandler exceptionHandler = new CanalThreadUncaughtExceptionHandler();
        BasicThreadFactory factory = new BasicThreadFactory.Builder()
                .namingPattern("ExecutorService-canal-thread-%d")
                .uncaughtExceptionHandler(exceptionHandler)
                .build();
        //ExecutorService executorService = Executors.newFixedThreadPool(20, factory);
        ExecutorService executorService = new ThreadPoolExecutor(processors, processors,
                30L, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(),
                factory);
        return executorService;
    }
}
